﻿using Finance.Infrastructrue.Interface;
using Finance.API.Write.Application.Command.ReceivablesManagementCommand;
using Finance.Domain;
using Finance.ErrorCode;
using MediatR;
using AutoMapper;
using Finance.Infrastructrue.Implement;
using System.Transactions;
using Azure;

namespace Finance.API.Write.Application.Hander.ReceivablesManagementHander
{
    public class UpdReceivablesManagementHander : IRequestHandler<UpdReceivablesManagementCommand ,APIResult<int>>
    {
        DatabaseContext db;
        IBaseRepository<ReceivablesManagement> recRep;
        ILogger<UpdReceivablesManagementHander> logger;
        IMapper mapper;

        public UpdReceivablesManagementHander(DatabaseContext db, IBaseRepository<ReceivablesManagement> recRep, ILogger<UpdReceivablesManagementHander> logger, IMapper mapper)
        {
            this.db = db;
            this.recRep = recRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public  async Task<APIResult<int>> Handle(UpdReceivablesManagementCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
               
                    //查询该编号是否重复
                    var mls = db.SqlSugar.Queryable<ReceivablesManagement>().Count(a => !a.IsDel && a.FlowingWaterNumber == request.FlowingWaterNumber);
                    if (mls > 1)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "该编号已存在";
                        return await Task.FromResult(result);
                    }

                    //应收
                    var receivablesManagement = mapper.Map<ReceivablesManagement>(request);
                    receivablesManagement.IsDel = false;

                if (request.rid == 2)
                {

                    
                        //找到统一的生产编号
                        var Node = await db.SqlSugar.Queryable<ReceivablesManagement>().Where(a => !a.IsDel && a.FlowingWaterNumber == receivablesManagement.FlowingWaterNumber).FirstAsync();

                        //财务记账
                        FinancialBookkeeping financial = new FinancialBookkeeping()
                        {
                            FlowingWaterNumber = receivablesManagement.FlowingWaterNumber,
                            FinancialBookkeepingName = receivablesManagement.ReceivablesManagementName,
                            FinancialBookkeepingType = Node.ReceivablesManagementType,
                            BeneficiaryOrPayer = receivablesManagement.Payer,
                            PaymentAmount = receivablesManagement.PaidInAmount,
                            PaymentStype = receivablesManagement.ReceivablesManagementType,
                            Type = "应收",
                            PaymentTime = DateTime.Now,
                            PaymentInstitutions = receivablesManagement.PaymentInstitutions,
                            CreatTime = receivablesManagement.CreatTime,
                            CreatName = receivablesManagement.CreatName,
                            UpdateTime = receivablesManagement.UpdateTime,
                            UpdateName = receivablesManagement.UpdateName,
                            DeleteTime = receivablesManagement.DeleteTime,
                            DeleteName = receivablesManagement.DeleteName,
                            IsDel = receivablesManagement.IsDel
                        };
                        await db.SqlSugar.Insertable(financial).ExecuteCommandAsync();
                    }
                
                    

                    var m = await db.SqlSugar.Updateable(receivablesManagement).ExecuteCommandAsync();

                   



                    if (m > 0)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "应收管理修改成功";
                        result.Data = m;
                    }
                    else
                    {
                        result.Code = APIEnum.Fail;
                        result.Message = "应收管理修改失败";
                        result.Data = m;
                    }
                
                    

               
                
                
            }
            catch (Exception ex)
            {
                logger.LogError( "应收管理修改报错" + ex.Message);
                throw;
            }
            return await Task.FromResult(result);
        }
    }
}
